package vip.yyzhu.redisadmin.aop.permissions;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import vip.yyzhu.redisadmin.jopo.ResJson;
import vip.yyzhu.redisadmin.redis.RedisList;
import vip.yyzhu.redisadmin.util.Tool;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

// @SuppressWarnings("all")
@Aspect
@Component
@Order(1)
public class AuthTokenAspect {
    @Autowired
    RedisList redisList;
    /**
     * Spring中使用@Pointcut注解来定义方法切入点
     *
     * @Pointcut 用来定义切点，针对方法  @Aspect 用来定义切面，针对类
     * 后面的增强均是围绕此切入点来完成的
     * 此处仅配置被我们刚才定义的注解：AuthToken修饰的方法即可
     */
    @Pointcut("@annotation(authUnique)")
    public void doAuthUnique(AuthUnique authUnique) {
    }

    @Pointcut("@annotation(verifyKeyType)")
    public void doVerifyKeyType(vip.yyzhu.redisadmin.aop.verifyKeyType.VerifyKeyType verifyKeyType) {
    }


    /**
     * 此处使用环绕增强，在方法执行之前或者执行之后均会执行。)
     */
    @Around("doAuthUnique(*) || doVerifyKeyType(*)")
    public Object deBefore(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("验证是否连接");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String unique = Tool.getUnique(request);
        // System.out.println(unique);
        // if(unique == null){
        //     return new ResJson(4015, "参数不完整");
        // }
        Map res = new HashMap();
        if(redisList.getData(unique) == null){
            res.put("err", "没有连接");
            return new ResJson(4014, "没有连接",res);
        }
        if (!redisList.getJedis(unique).ping().equals("PONG")){
            redisList.del(unique);
            res.put("err", "连接丢失");
            return new ResJson(4014, "连接丢失",res);
        }

        // System.out.println(pjp.getSignature());
        // Object[] args = pjp.getArgs();
        // for (Object arg : args) {
        //     System.out.println(arg);
        // }
        //修改传入参数
        // processInputArg();

        // 执行原方法，并记录返回值。
        Object proceed = pjp.proceed();
        System.out.println("验证是否连接->");
        System.out.println(proceed);
        return proceed;
    }

}
